import React from 'react'
import { Form, Input, Button, Dialog } from 'antd-mobile'
import { useState, useRef } from "react"
import Time from '../../comments/time/time'
import { LoginApi } from '../../api/modules/user'
import { loginAsunc } from '../../store/modules/userSlice'
import { useSelector, useDispatch } from 'react-redux'
import { useNavigate, useSearchParams } from "react-router-dom"

function Login() {
    const [searchparams] = useSearchParams()
    const navigate = useNavigate()
    const dispatch = useDispatch()
    const [num, setnum] = useState(true)
    const shouRef = useRef(null)
    function sendbian() {
        if (shouRef.current.nativeElement) {
            if (shouRef.current.nativeElement.value) {
                setnum(false)
            } else {
                Dialog.alert({
                    content: '手机号不能为空',
                })
            }

        }

    }
    function send() {
        if (num) {
            return <a onClick={() => { sendbian() }}>发送验证码</a>
        } else {
            return <Time tiem={20} tiemChildren={() => { setnum(true) }} />
        }
    }
    function loginRes(info) {
        dispatch(loginAsunc(info)).then(res => {
            if (res.payload.code == 0) {
                let next = searchparams.get("next")
                if (next) {
                    navigate(next)
                } else {
                    navigate("/")
                }
            } else {
                Dialog.alert({
                    content: res.payload.msg,
                })

            }
        })

        // LoginApi(info).then(res => {
        //     console.log(res, "{[[[[[");
        // })
    }
    return (
        <Form layout='horizontal' mode='card'
            footer={
                <Button block type='submit' color='primary' size='large'>
                    提交
                </Button>
            }
            initialValues={{
                rel: "123456",
                code: "123"
            }}
            onFinish={(values) => { loginRes(values) }}
        >
            <Form.Item name='rel' label='手机号' rules={[{ required: true, message: '手机号不能为空!' }]}  >
                <Input ref={shouRef} placeholder='请输入手机号' />
            </Form.Item>
            <Form.Item name='code' label='短信验证码' extra={send()} rules={[{ required: true, message: '验证码不能为空!' }]}>
                <Input placeholder='请输入' />
            </Form.Item>
        </Form>
    )
}
export default Login